<?php
/**
 * 银行详情
 */
namespace app\api\modules\v1\bank\models;


use app\api\components\ApiModel;
use Yii;
use app\models\base\User;
use app\models\base\Project;
use app\models\base\Activity;
use app\models\base\BankAccount;
use app\models\base\Bank;
use app\api\modules\v1\market\models\AppUser;
use \yii\helpers\ArrayHelper;
use \yii\data\Pagination;
use app\backend\widgets\LinkPager;
use \yii\db\Query;
use app\api\modules\v1\market\models\UrlHandler;

class BankApp extends ApiModel
{
	public static function getBank()
	{
        $list = [];
        $bank = ArrayHelper::toArray(Bank::findOne(['bank_id'=>1]));

        //获取银行的价值等等
		$data = AppUser::getInfo();
        $list = [
            'name' => $bank['name'],
            'create_time' => date('Y-m-d',$bank['create_time']),
            'finish_time' => '未结束',
            'continue_time' => ceil((time()-$bank['create_time'])/(3600*24)),
            'value' => round($data['value']/8,1),
            'gold' => round($data['gold']/8,1),
            'cost' => round($data['cost']/8,1),
            'vcost' => $data['cost']?round($data['value']/$data['cost'],2):0,
            'gcost' => $data['cost']?round($data['gold']/$data['cost'],2):0,
            'vgold' => $data['gold']?round($data['value']/$data['gold'],2):0,
        ];
        return $list;
	}


    public static function getOwnBank($bankaccount)
    {
        foreach($bankaccount as $k => $v){
            $name = User::findOne($v['user_id'])['name'];
            $data[$k] = [
                'account_id' => $v['account_id'],
                'user_id' => $v['user_id'],
                'name' => $name,
                'all_cost' => round($v['all_cost']/8,1),
                'all_gold' => round($v['all_gold']/8,1),
                'all_value' => round($v['all_value']/8,1),
                'vcost' => $v['all_cost']?round($v['all_value']/$v['all_cost'],2):0,
                'gcost' => $v['all_cost']?round($v['all_gold']/$v['all_cost'],2):0,
                'vgold' => $v['all_gold']?round($v['all_value']/$v['all_gold'],2):0,

            ];
        };

        return $data;

    }

    /**
     * [分页]
     * @param  [query] $query [description]
     * @return [array]        [description]
     */
    public static function pagination($query,$pagesize,$page)
    {
        $clonequery = clone $query;
        $counts = count($clonequery->all());
        if($page>ceil($counts/$pagesize)){
            return ['list'=>[],'pagesize'=>''];
        };
        $pages = new Pagination([
                'totalCount' => $counts,
                'defaultPageSize' => $pagesize,
            ]);
        $query->limit($pages->limit);
        $query->offset($pages->offset);
        $list = $query->all();
        $pagesize = LinkPager::widget([
                    'pagination' => $pages,
                    'firstPageLabel' => "首页",
                    'prevPageLabel' => '上一页',
                    'nextPageLabel' => '下一页',
                    'lastPageLabel' => '末页',
                ]);

        return ['list'=>$list,'pagesize'=>$pagesize];
    } 


    /**
     * [银行明细个人信息]
     * @param  [string] $account_id [个人银行id]
     * @return [array]             [信息数组]
     */
    public static function getownerinfo($account_id)
    {
        $account = (new \yii\db\Query())->select(['account_id','ba.start_time as start_time','ba.finish_time as finish_time','all_cost','all_value','all_gold','user.name as name'])
                        ->from(BankAccount::tableName().' AS ba')
                        ->where(['ba.account_id'=>$account_id,'ba.disabled'=>0])
                        ->innerJoin(User::tableName().' AS user','ba.user_id=user.user_id')
                        ->one();
        if(empty($account)){
            return false;
        }
        //时间格式化
        $account = self::formattime($account);
        //将价值等转化为人/天格式(因为存入格式为人/时)
        $account = self::getNewInfo($account);
        // echo '<pre>'; var_dump($account); echo '</pre>';exit;
        return $account;

    }

    public static function getNewInfo($account)
    {
        $account['all_value'] = round($account['all_value']/8,1);
        $account['all_gold'] = round($account['all_gold']/8,1);
        $account['all_cost'] = round($account['all_cost']/8,1);
        return $account;
    }

    /**
     * [处理时间]
     * @param  [array] $account [description]
     * @return [array]          [description]
     */
    public static function formattime($account)
    {
        //存在开始时间
        if($account['start_time']){
            //存在结束时间
            if($account['finish_time']){
                $account['finish_time'] = date('Y-m-d',$account['finish_time']);
                $account['continue_time'] = ceil(($account['finish_time']-$account['start_time'])/(3600*24));
            }else{
                $account['finish_time'] = '未结束';
                $account['continue_time'] = ceil((time()-$account['start_time'])/(3600*24));
            }
            $account['start_time'] = date('Y-m-d',$account['start_time']);
        }else{
            $account['start_time'] = '未开始';
            $account['continue_time'] = '0';
            $account['finish_time'] = '未结束';
        }
        

        return $account;
    } 

    /**
     * [明细表处理格式]
     * @param [array] $data [description]
     * @return [array] $data [格式化后的数组]
     */
    public function Formatdata($data)
    {
        foreach($data['list'] as $k => $v){
            //处理活动类型
            if($v['type'] == 0){
                $data['list'][$k]['type'] = '需求';
            }elseif($v['type'] == 1){
                $data['list'][$k]['type'] = '需求优化';
            }elseif($v['type'] == 2){
                $data['list'][$k]['type'] = '需求变更';
            }elseif($v['type'] == 3){
                $data['list'][$k]['type'] = '开发设计';
            }elseif($v['type'] == 4){
                $data['list'][$k]['type'] = 'BUG';
            }else{
                $data['list'][$k]['type'] = '任务';
            };
            //处理状态
            switch ($v['status']) {
                case 0:
                    $data['list'][$k]['status_name'] = '未开始';
                    break;
                case 1:
                    $data['list'][$k]['status_name'] = '进行中';
                    break;
                case 2:
                    $data['list'][$k]['status_name'] = '阻塞';
                    break;
                case 3:
                    $data['list'][$k]['status_name'] = '完成';
                    break;
                case 4:
                    $data['list'][$k]['status_name'] = '待审核';
                    break;
                // case 5:
                //     $data[$k]['status'] = '已入账';
                //     break;
                default:
                    $data['list'][$k]['status_name'] = '已入账';
                    break;
            }
            //处理创建时间
            $data['list'][$k]['create_time'] = date('Y-m-d',$v['create_time']);

            //创建人格式化
            $data['list'][$k]['apply_user_id'] = self::getapplyname($v['apply_user_id']);

            //处理人格式化
            $data['list'][$k]['handler_user_id'] = self::gethandlername($v['handler_user_id']);

            //处理项目名称
            $data['list'][$k]['project_name'] = self::getproname($v['project_id']);

        }

        return $data;
    }

    /**
     * [创建人格式化]
     * @param  [type] $apply_user_id [创建人id]
     * @return [type]                [创建人名称]
     */
    public static function getapplyname($apply_user_id)
    {
        return $apply_user_name = User::findOne($apply_user_id)['name'];
    }

    /**
     * [处理人格式化]
     * @param  [type] $apply_user_id [处理人id]
     * @return [type]                [处理人名称]
     */
    public static function gethandlername($handler_user_id)
    {
        return $handler_user_name = User::findOne($handler_user_id)['name'];
    } 

    /**
     * [项目名称格式化]
     * @param  [type] $apply_user_id [项目id]
     * @return [type]                [项目名称]
     */
    public static function getproname($project_id)
    {
        return $pro_name = Project::findOne($project_id)['name'];
    } 


    /**
     * @param $get      $_GET数组
     * @param $query    $query对象
     * @return mixed    返回$query带有时间查询条件的query对象
     */
    public static function getQueryByTime($get,$query)
    {
        if(!isset($get['create_time'])){
            return $query;
        }

        //今天
        $begin_today = mktime(0,0,0,date('m'),date('d'),date('Y'));
        $end_today   = mktime(0,0,0,date('m'),date('d'),date('Y'))+24*3600;
        $dayOfWeek = date('w')==0?7:date('w');
        switch ($get['create_time']) {
            case 0:

                //今天
                $time = [$begin_today,$end_today];
                break;
            case 1:

                //昨天
                $time = [$begin_today-24*3600,$end_today-24*3600];
                break;
            case 2:

                //最近三天
                $time = [$begin_today-2*24*3600,$end_today-24*3600*2];
                break;
            case 3:

                //本周
                $time = [$begin_today-($dayOfWeek-1)*24*3600,$end_today];
                break;
            case 4:

                //上周
                $time = [$begin_today-($dayOfWeek-1-7)*24*3600,$end_today-($dayOfWeek+6)*24*3600];

                break;
            case 5:

                //本月
                $time = [
                            mktime(0,0,0,date('m'),1,date('Y')),
                            mktime(23,59,59,date('m'),date('d'),date('Y')),
                        ];
                break;
            case 6:
                $day = date('d',mktime(1,0,0,date('m')-1,2,date('Y')));
                //上月
                $time = [
                    mktime(0,0,0,date('m')-1,1,date('Y')),
                    mktime(23,59,59,date('m')-1,$day,date('Y')),
                ];
                break;
            case 7:

                //今年
                $time = [
                    mktime(0,0,0,1,1,date('Y')),
                    mktime(23,59,59,date('m'),date('d'),date('Y')),
                ];
                break;
            case 8:
                //去年
                $time = [
                    mktime(0,0,0,1,1,date('Y')-1),
                    mktime(23,59,59,12,31,date('Y')-1),
                ];
                break;
            default:

                //全部
                $time =[];
                break;
        }


        return empty($time) ? $query : $query -> andWhere([
            'and',
            ['>=', 'create_time' , $time[0]],
            ['<' , 'create_time' , $time[1]]
        ]) ;


    }


    /**
     * [rangeinfo 根据不同的时间段查询个人银行信息]
     * @param  [type] $get  [get传值]
     * @param  [type] $page [页码]
     * @return [type]       [description]
     */
    public static function rangeinfo($get,$page)
    {
        $query = (new Query())->select(['user.name as name','handler_user_id as user_id','SUM(all_cost)/8 as all_cost','SUM(surplus_value)/8 as all_value','SUM(surplus_gold)/8 as all_gold','FORMAT(SUM(surplus_value)/SUM(all_cost),2) as vcost','FORMAT(SUM(surplus_gold)/SUM(all_cost),2) as gcost','FORMAT(SUM(surplus_value)/SUM(surplus_gold),2) as vgold'])->from(Activity::tableName().' AS act')->where(['status'=>5])->groupBy('handler_user_id')
            ->innerJoin(User::tableName().' AS user','user.user_id=act.handler_user_id')
            ->andWhere(['user.disabled'=>0]);
        $query = UrlHandler::handle_get($query,$get,['page','status']);

        $query = self::getQueryByReviewTime($get,$query);

        $data = self::pagination($query,20,$page);
        return $data;
    }

    /**
     * @param $get      $_GET数组
     * @param $query    $query对象
     * @return mixed    返回$query带有时间查询条件的query对象
     */
    public static function getQueryByReviewTime($get,$query)
    {
        //今天
        $begin_today = mktime(0,0,0,date('m'),date('d'),date('Y'));
        $end_today   = mktime(0,0,0,date('m'),date('d'),date('Y'))+24*3600;
        $dayOfWeek = date('w')==0?7:date('w');
        switch ($get['status']) {
            case 1:

                //今天
                $time = [$begin_today,$end_today];
                break;
            case 2:

                //昨天
                $time = [$begin_today-24*3600,$end_today-24*3600];
                break;
            case 3:

                //最近三天
                $time = [$begin_today-2*24*3600,$end_today];
                break;
            case 4:

                //本周
                $time = [$begin_today-($dayOfWeek-1)*24*3600,$end_today];
                break;
            case 5:

                //上周
                $time = [$begin_today-($dayOfWeek-1-7)*24*3600,$end_today-($dayOfWeek+6)*24*3600];

                break;
            case 6:

                //本月
                $time = [
                            mktime(0,0,0,date('m'),1,date('Y')),
                            mktime(23,59,59,date('m'),date('d'),date('Y')),
                        ];
                break;
            case 7:
                $day = date('d',mktime(1,0,0,date('m')-1,2,date('Y')));
                //上月
                $time = [
                    mktime(0,0,0,date('m')-1,1,date('Y')),
                    mktime(23,59,59,date('m')-1,$day,date('Y')),
                ];
                break;
            case 8:

                //今年
                $time = [
                    mktime(0,0,0,1,1,date('Y')),
                    mktime(23,59,59,date('m'),date('d'),date('Y')),
                ];
                break;
            case 9:
                //去年
                $time = [
                    mktime(0,0,0,1,1,date('Y')-1),
                    mktime(23,59,59,12,31,date('Y')-1),
                ];
                break;
            default:

                //全部
                $time =[];
                break;
        }


        return empty($time) ? $query : $query -> andWhere([
            'and',
            ['>=', 'review_time' , $time[0]],
            ['<' , 'review_time' , $time[1]]
        ]) ;


    }
}